/*
 * Copyright (C) 2009 Tony Gentilcore
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.scoreninja;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

/**
 * Manages an asynchronous HTTP request.
 * 
 * @author tonygentilcore@gmail.com (Tony Gentilcore)
 */
final class AsyncHttpRequest extends Thread {
  private static final String ENCODING = "UTF-8";
  private final String mURL;
  private final Handler mHandler;

  /**
   * Start an asynchronous HTTP operation.
   * 
   * @param url The URL of the request.
   * @param cb The AsyncCallback object you want to be notified when the
   *          operation completes.
   */
  public AsyncHttpRequest(String url, Handler handler) {
    super();
    mURL = url;
    mHandler = handler;
    start();
  }

  public void run() {
    Bundle b = new Bundle();

    try {
      HttpURLConnection conn = (HttpURLConnection) (new URL(mURL))
              .openConnection();
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.connect();
      b.putString("response", toString(conn.getInputStream()));
      conn.disconnect();
    } catch (IOException e) {
      // TODO Save requests for when online.
      b.putString("response", "");
    }
    
    if (mHandler != null) {
      Message msg = mHandler.obtainMessage();
      msg.setData(b);
      mHandler.sendMessage(msg);
    }
  }

  /**
   * Reads an InputStream and returns its contents as a String. Also effects
   * rate control.
   * 
   * @param inputStream The InputStream to read from.
   * @return The contents of the InputStream as a String.
   */
  private static String toString(InputStream inputStream) throws IOException {
    StringBuilder outputBuilder = new StringBuilder();
    String string;
    if (inputStream != null) {
      BufferedReader reader = new BufferedReader(new InputStreamReader(
              inputStream, ENCODING));
      while (null != (string = reader.readLine())) {
        outputBuilder.append(string).append('\n');
      }
    }
    return outputBuilder.toString();
  }
}
